package gl.android.biyiqing.fragment;

import gl.App;
import gl.android.biyiqing.BYQBaseActivity;
import gl.android.biyiqing.FragmentContainerActivity;
import gl.android.biyiqing.R;
import gl.android.biyiqing.UserInfoActivity;
import gl.android.biyiqing.adapter.JsonArrayChatImageListAdapter;
import gl.android.biyiqing.api.API;
import gl.android.biyiqing.bean.BYQUserInfo;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.Tip;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 消息盒子
 * 
 * @author geliang
 * 
 */
public class MessageChatFragment extends BaseListFragmet implements
		OnClickListener {
	private static final int TYPE_POST = 0;
	private static final int TYPE_NOCOST = 1;
	protected final String ERR = "发送消息失败";
	protected final String OK = "发送成功";
	private TextView empty;
	private ListView list;
	protected String NOTFOUND = "没有消息";
	private Drawable drawable;
	private EditText et_msg;
	private View btn_send;
	private View ll_msg_sendtip;
	private String touserid;

	private void bindViews() {
		et_msg = (EditText) findViewById(R.id.et_msg);
		btn_send = findViewById(R.id.btn_send);
		ll_msg_sendtip = findViewById(R.id.ll_msg_sendtip);
		empty = (TextView) findViewById(R.id.empty);
		et_msg.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				btn_send.setEnabled(s == null || s.length() <= 0 ? false : true);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		findViewById(R.id.btn_send).setOnClickListener(this);
		findViewById(R.id.btn_send_post).setOnClickListener(this);
		findViewById(R.id.btn_helpwrite).setOnClickListener(this);
		findViewById(R.id.rl_useinfo).setOnClickListener(this);

		list = (ListView) findViewById(android.R.id.list);
		list.setEmptyView(empty);
		empty.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				initdata();
			}
		});

		empty.setText(NOTFOUND);

		empty.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null,
				null);

	}

	public static LoveAskListFragment newInstance() {
		LoveAskListFragment fragment = new LoveAskListFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_messagechat, container,
				false);
		drawable = getActivity().getResources().getDrawable(
				R.drawable.ic_talking_btn_mail_p);
		bindViews();
		initdata();
		getRight();
		return rootView;
	}

	int type = 0;

	private void getRight() {

		Object[] args = new Object[] { UserManger.getInstance().userid,
				touserid, };
		BaseControl.get(API.URL + "GetMessageRight?fuserid=%s&tuserid=%s",
				new AjaxCallBackProxy() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							if ("0".equals(new JSONObject(t).getString("msg"))) {
								return;
							}

							if ("1".equals(new JSONObject(t).getString("msg"))) {
								setMsgTypetoNoNeedPost();
								return;
							}
						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						Tip.show(ERR);
					}
				}, args);
	}

	boolean isNewMessage = false;

	private void initdata() {
		try {
			final String jsonArrayData = getArguments()
					.getString(KEY_JSON_DATA);
			touserid = getArguments().getString(KEY_TO_USER_ID);
			if (jsonArrayData != null && touserid != null) {
				findViewById(R.id.ll_msg_input).setVisibility(View.VISIBLE);
				bindDataToAbsListView(getListView(), new int[] {
						R.layout.item_list_chat_to,
						R.layout.item_list_chat_from }, new String[] {
						"username", "avatar", "content", "starttime" },
						new int[] { R.id.tv_nick, R.id.iv_avator, R.id.age,
								R.id.tv_jianjie }, jsonArrayData);
				getListView().setStackFromBottom(true);
			}
			else if (jsonArrayData == null && touserid != null) {
				isNewMessage = true;
				findViewById(R.id.rl_useinfo).setVisibility(View.INVISIBLE);
				getListView().setVisibility(View.INVISIBLE);
				empty.setVisibility(View.INVISIBLE);
				findViewById(R.id.ll_msg_input).setVisibility(View.VISIBLE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void bindDataToAbsListView(final AbsListView adpateview,
			final int[] itemLayout, final String[] from, final int[] to,
			String t) throws JSONException {
		// pre fromat data
		t = preFormatJsonData(t);
		adpateview.setAdapter(new JsonArrayChatImageListAdapter(getActivity(),
				new JSONObject(t).get("data").toString(), itemLayout, from, to,
				getOnItemChildViewCilck()));
		adpateview
				.setOnItemClickListener((OnItemClickListener) getOnItemListener(
						from, t));
		final JSONArray jsonArray = new JSONObject(t).getJSONArray("data");
		if (jsonArray.length() > 0) {
			final JSONObject jo = jsonArray.getJSONObject(0);
			App.mFBitmap.display(
					(ImageView) findViewById(R.id.imageView1),
					API.IMAGEURL
							+ jo.getString("avatar"));
			((TextView) findViewById(R.id.textView1)).setText(jo.getString("username"));
			((TextView) findViewById(R.id.textView2)).setText("最近联系时间:"+jo.getString("starttime"));
			String shenfen = String.format("%s岁/%scm/%s/%s",
					BYQUserInfo.getReadableAge(jo.optString("age", "0")),
					jo.optInt("height", 0),
					BYQUserInfo.getReadable("学历", jo.optInt("education", 0)),
					BYQUserInfo.getReadable("职业", jo.optInt("jobs", 0)));
			((TextView) findViewById(R.id.textView3)).setText(shenfen/*jo.getString("height")+"/"+jo.getString("age")*/);
			
			int iconId = R.drawable.ic_vip;
//			用户组ID：1普通会员 2高级会员 3.皇冠会员 3钻石会员、用户形象照
			switch (jo.optInt(BYQUserInfo.KEY_GROUPID, 0)) {
			case 1:
				iconId = R.drawable.ic_member_general;
				break;
			case 2:
				iconId = R.drawable.ic_member_crystal;
				break;
			case 3:
				iconId = R.drawable.ic_member_crown;
				break;
			case 4:
				iconId = R.drawable.ic_member_diamond;
				break;
			}
			jo.put(BYQUserInfo.KEY_GROUP, iconId);
			if (jo.optInt("online", 0)==1) {
				jo.put(BYQUserInfo.KEY_VIP_UNIT, R.drawable.ic_vip);
			}else{
				jo.put(BYQUserInfo.KEY_VIP_UNIT,0 );
			}
			((ImageView) findViewById(R.id.iv_online)).setImageResource(jo.optInt(BYQUserInfo.KEY_VIP_UNIT));
			((ImageView) findViewById(R.id.iv_vip)).setImageResource(jo.optInt(BYQUserInfo.KEY_GROUP));
		}
	}

	@Override
	public void onClick(View v) {
		if (R.id.rl_useinfo == v.getId()) {
			Intent intent = new Intent(getActivity(), UserInfoActivity.class);
				intent.putExtra(BYQBaseActivity.KEY_USER_ID, touserid);
				startActivity(intent);
			return;
		}
		if (R.id.btn_helpwrite == v.getId()) {
			// GetMessageHelp?sex=1
			Object[] args = new Object[] { UserManger.getInstance().userinfo
					.getGender() };
			BaseControl.get(API.URL + "GetMessageHelp?sex=%s",
					new AjaxCallBackProxy() {
						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							try {
								if ("0".equals(new JSONObject(t)
										.getString("msg"))) {
									Tip.show("帮写失败");
									return;
								}

								if ("1".equals(new JSONObject(t)
										.getString("msg"))) {
									dataJSONArray = new JSONObject(t)
											.getJSONArray("data");
									et_msg.setText(dataJSONArray.getJSONObject(
											0).getString("greeting"));
									initdata();
									return;
								}
							} catch (Exception e) {
								e.printStackTrace();
								onFailure(e, 0, e.getMessage());
							}
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							Tip.show(ERR);
						}
					}, args);
			return;
		}
		if (R.id.btn_send_post == v.getId()) {
			type = TYPE_POST;
		}
		else {
			type = TYPE_NOCOST;
		}

		Editable input = et_msg.getText();
		if (TextUtils.isEmpty(input)) {
			Tip.show("内容不能是空白的,使用'帮我写'试试");
			return;
		}

		Object[] args;
		try {
			args = new Object[] { UserManger.getInstance().userid, touserid,
					URLEncoder.encode(input.toString(), "UTF-8"),
					String.valueOf(type) };
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			args = new Object[] { UserManger.getInstance().userid, touserid,
					input.toString(), String.valueOf(type) };
		}
		BaseControl.get(API.URL
				+ "SendMessage?fuserid=%s&tuserid=%s&content=%s&type=%s",
				new AjaxCallBackProxy() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							if ("0".equals(new JSONObject(t).getString("msg"))) {
								Tip.show(ERR);
								return;
							}
							if ("2".equals(new JSONObject(t).getString("msg"))) {
								Tip.show("邮票不足,发送失败");
								return;
							}
							if ("1".equals(new JSONObject(t).getString("msg"))) {
								Tip.show(OK);
								if (isNewMessage) {
									getActivity().onBackPressed();
								}
								else {
									et_msg.setText("");
									refresh();
									getRight();

								}
								return;
							}
						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						Tip.show(ERR);
					}
				}, args);

	}

	protected void refresh() {
		BaseControl.get(getArguments().getString("uri")+"%s",
				new AjaxCallBackProxy() {

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {

							if ("2".equals(new JSONObject(t).getString("msg"))) {
								getArguments().putString(KEY_JSON_DATA, t);
								initdata();
								return;
							}

						} catch (Exception e) {
							e.printStackTrace();
							onFailure(e, 0, e.getMessage());
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
						Tip.show(ERR);
					}
				}, new Object[]{""});

	}

	public void setMsgTypetoNoNeedPost() {
		final Animation loadAnimation = AnimationUtils.loadAnimation(
				getActivity(), android.R.anim.fade_out);
		loadAnimation.setDuration(800);
		ll_msg_sendtip.startAnimation(loadAnimation);
		ll_msg_sendtip.setVisibility(View.GONE);
	}

}